package com.cmfi.service.impl.userRoleAuthImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.cmfi.SpringbootApplication;
import com.cmfi.dao.userRoleAuthDao.UserDao;
import com.cmfi.domain.userRoleAuthEntity.AjaxResult;
import com.cmfi.domain.userRoleAuthEntity.LoginUser;
import com.cmfi.domain.userRoleAuthEntity.User;
import com.cmfi.service.inter.userRoleAuthInter.LoginService;
import com.cmfi.utils.Cache;
import com.cmfi.utils.JwtUtils;

@Service
public class LoginServiceImpl implements LoginService {
	@Autowired
	private UserDao userDao;
	@Resource
    private AuthenticationManager authenticationManager;
	 static Logger logger = LoggerFactory.getLogger(SpringbootApplication.class);
    @Autowired
    private Cache cache;

    @Override
    public AjaxResult login(User user) {
		AjaxResult ajax = AjaxResult.success();
		// AuthenticationManager authenticate 进行用户认证
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
				user.getUsername(), user.getPassword());
		Authentication authenticate = authenticationManager.authenticate(authenticationToken);
		// 如果认证没通过，给出对应的提示
		if (Objects.isNull(authenticate)) {
			throw new RuntimeException("登录失败");
		}
		// 如果认证通过了，使用userid生成一个jwt jwt存入ajax
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		Long userId = loginUser.getUser().getId();
		Map<String, Object> map = new HashMap<>();
		map.put(JwtUtils.DETAILS_USER_ID, userId);
		String token = JwtUtils.createToken(map);
		ajax.put("id_token", token);
		// 把完整的用户信息存入redis useri1d作为key
		cache.setCacheObject("login:" + userId, loginUser);
		return ajax;
    }

    @Override
    public AjaxResult logout() {
        //获取SecirityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        //删除redis中的值
        cache.deleteObject("login:" + id);
        return AjaxResult.success();
    }

}
